#include "tcpserver.h"
#include "tcpserverdispatcher.h"
#include "tcpserverconnection.h"

TcpServer::TcpServer(TcpServerConnectionFactory* pFactory, 
        ThreadPool& threadPool,const ServerSocket& socket):
    m_socket(socket),
    m_pDispatcher(new TcpServerDispatcher(pFactory, threadPool)),
    m_stopped(true)
{
}

TcpServer::~TcpServer()
{
    stop();
}

void TcpServer::start()
{
    m_stopped = false;
    m_thread.start(*this);
}

void TcpServer::stop()
{
    if (!m_stopped)
    {
        m_stopped = true;
        m_pDispatcher->stop();
        m_thread.join();
    }
}

void TcpServer::run()
{
    while (!m_stopped)
    {
        // 1 sec
        if (m_socket.poll(1000, Socket::SELECT_READ))
        {
            int fd = m_socket.acceptConnection();
            // enabe nodelay default
            Socket::setNoDelay(fd,true);
            m_pDispatcher->enqueue(fd);
        }
    }
}



